<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogFormVisible"
    width="700px"
    @close="close"
  >
    <el-form ref="form" label-width="100px" :model="form" :rules="rules" :disabled="disabled">
      <el-form-item label="属性规格" prop="name">
        <el-input v-model.trim="form.name" clearable/>
      </el-form-item>
      <el-form-item label="属性编码" prop="code">
        <el-row type="flex" align="middle">
          <el-col :span="20">
            <el-input v-model.trim="form.code" clearable readonly/>
          </el-col>
          <el-col :span="1" class="gap"></el-col>
          <el-col :span="4" class="text-right">
            <el-button icon="el-icon-plus" type="" @click="pinyin()">获取编码</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="输入类型" prop="input_type">
        <el-select v-model.trim="form.input_type" clearable>
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生产属性">
        <el-switch
          v-model="form.production_attribute"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>

      <el-card class="box-card" style="margin-top: 20px" v-if="form.input_type == 2">
        <div slot="header" class="clearfix">
          <span>枚举内容</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="handleAddRow">添加</el-button>
        </div>
        <el-table :data="form.object" border style="width: 100%" :max-height="300">
          <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
          <el-table-column prop="name" :label="form.name" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="请输入内容"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="250">
            <template #default="scope">
              <el-button type="primary" icon="el-icon-arrow-up" circle plain @click.stop="handleUp(scope.$index)"/>
              <el-button type="warning" icon="el-icon-arrow-down" circle plain @click.stop="handleDown(scope.$index)"/>
              <el-button type="danger" icon="el-icon-delete" circle plain @click.stop="handleDel(scope.$index)"/>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :disabled="disabled" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {doEdit, getPinYin} from '@/api/sku/cate_value'
import {getAdminListByRole} from "@/api/manage/adminUser";
import Upload from '@/views/other/upload/SingleImage3'

export default {
  name: 'customerEdit',
  components: {Upload},
  data() {
    return {
      options: [
        {value: 1, label: '文本'},
        {value: 2, label: '枚举'},
        {value: 3, label: '日期'},
        {value: 4, label: '数字'},
        {value: 5, label: '百分比'},
      ],
      disabled: false,
      form: {
        code: '',
        input: 0,
        object: []
      },
      rules: {
        code: [
          {required: true, trigger: 'blur', message: '请填写编码'},
        ],
        name: [
          {required: true, trigger: 'blur', message: '请填写属性规格'},
        ],
        input_type: [
          {required: true, trigger: 'blur', message: '请选择'},
        ]
      },
      title: '',
      dialogFormVisible: false,
      mainList: [],
      fileRootPath: process.env.VUE_APP_FILE_ROOT_PATH

    }
  },
  created() {
  },
  methods: {
    handleAddRow() {
      this.form.object.push({
        name: '',
      });
    },
    handleDel(index) {
      this.form.object.splice(index, 1);
    },
    handleUp(index) {
      if (index > 0) {
        const temp = this.form.object[index];
        this.$set(this.form.object, index, this.form.object[index - 1]);
        this.$set(this.form.object, index - 1, temp);
      }
    },
    handleDown(index) {
      if (index < this.form.object.length - 1) {
        const temp = this.form.object[index];
        this.$set(this.form.object, index, this.form.object[index + 1]);
        this.$set(this.form.object, index + 1, temp);
      }
    },
    delete_file() {
      this.form.file_path = ''
    },
    pinyin() {
      getPinYin({'name': this.form.name}).then(response => {
        this.form.code = response.data.code
      })
    },
    forceUpdate() {
      this.$forceUpdate()
    },
    showEdit(row) {
      if (!row) {
        this.title = '添加'
      } else {
        this.title = '编辑'
        this.form = Object.assign({}, row)
        this.form.temp_old = this.form.file_path
      }
      this.dialogFormVisible = true
      this.disabled = false
    },
    viewEdit(row) {
      this.title = '查看'
      this.form = Object.assign({}, row)
      this.dialogFormVisible = true
      this.disabled = true

    },
    close() {
      this.$refs['form'].resetFields()
      this.form = this.$options.data().form
      this.dialogFormVisible = false
    },
    hasDuplicates(arr) {
      const seen = new Set();
      for (const obj of arr) {
        const str = JSON.stringify(obj);
        if (seen.has(str)) {
          return str; // 返回重复项的字符串表示
        }
        seen.add(str);
      }
      return false; // 没有重复
    },
    save() {
      const duplicate = this.hasDuplicates(this.form.object);
      if (duplicate) {
        let result = duplicate.replace(/[{}]/g, '').replace(/"name":/g, '').replace(/"/g, '');
        this.$baseMessage(`枚举选项重复: ${result}, 请重新填写`, 'error', 'vab-hey-message-error');
      } else {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            const {msg} = await doEdit(this.form)
            this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            this.$emit('fetch-data')
            this.close()
          }
        })
      }

    },
  },
}
</script>
<style scoped>
.row-with-margin {
  margin-bottom: 5px; /* 你可以根据需要调整这个值 */
}

.gap {
  /* 如果你已经有了gap类，确保它不会影响布局 */
}
</style>
